package cn.jnetty.remoting;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 猪哥亮
 * @email 1030681978@qq.com
 * @date 2020/4/2 16:25
 * 描述：
 */
public class JnettyThreadFactory  implements ThreadFactory {
    private final AtomicInteger threadCounter = new AtomicInteger(1);
    private final String name;
    private final boolean hasSuffix;
    private final ThreadGroup group;

    public JnettyThreadFactory(String name) {
        this(name, true);
    }

    public JnettyThreadFactory(String name, boolean hasSuffix) {
        final SecurityManager securitymanager = System.getSecurityManager();
        this.group = securitymanager == null ? Thread.currentThread().getThreadGroup() : securitymanager.getThreadGroup();
        this.name = name;
        this.hasSuffix = hasSuffix;
    }
    @Override
    public Thread newThread(Runnable runnable) {
        StringBuilder threadName = new StringBuilder(56);
        threadName.append(name);
        if (hasSuffix) {
            threadName.append("-").append(threadCounter.getAndIncrement());
        }

        Thread thread = new Thread(group, runnable, threadName.toString());
        if (thread.isDaemon()) {
            thread.setDaemon(false);
        }
        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
}
